<?php

class IndexAction extends CommonAction
{
    public function index()
	{
		check_system();
		
		if (phpversion() < '5.0') {
			$this->assign('var001','no');
		}else{
			$this->assign('var001','ok');
		}

		if (!ini_get('file_uploads')) {
			$this->assign('var002','no');
		}else{
			$this->assign('var002','ok');
		}
	
		if (ini_get('session.auto_start')) {
			$this->assign('var003','no');
		}else{
			$this->assign('var003','ok');
		}
		
		if (!extension_loaded('mysql')) {
			$this->assign('var004','no');
		}else{
			$this->assign('var004','ok');
		}
				
		if (!extension_loaded('gd')) {
			$this->assign('var005','no');
		}else{
			$this->assign('var005','ok');
		}

		if (!extension_loaded('curl')) {
			$this->assign('var006','no');
		}else{
			$this->assign('var006','ok');
		}

		if (!function_exists('mcrypt_encrypt')) {
			$this->assign('var007','no');
		}else{
			$this->assign('var007','ok');
		}
				
		if (!extension_loaded('zlib')) {
			$this->assign('var008','no');
		}else{
			$this->assign('var008','ok');
		}
	
		if (!is_writable(C('APP_PATH_DIY') . '/web_config_diy.php')) {
			$this->assign('var009','no');
		}else{
			$this->assign('var009','ok');
		}
		
		if (!function_exists(file_get_contents)) {
			$this->assign('var010','no');
		}else{
			$this->assign('var010','ok');
		}
		
		//$this->assign("username",$_SESSION[C('USER_AUTH_TIT')]);
		vendor('MisoneAction.misone#action');
		$mac = new GetMacAddr(PHP_OS);
		$reginfo = $mac->mac_addr;
	
		$cloud_http_post_url=C('OFFICIAL_URL')."/index.php/Index/api_get_server_info?request_code=".$reginfo."&dt=".strtotime(date('Y-m-d H:i:s'));
		$vconf = stream_context_create(array(  
			'http' => array(  
			'timeout' => 3 //秒  
			)  
		)  
		);
		$result=file_get_contents($cloud_http_post_url,0,$vconf);
		if(stripos($result,'~~ok~~')===false)
		{
			$result='';
		}else{
			$result=str_ireplace('~~ok~~','',$result);
		}		
		$this->assign('server_info',$result);
		//var_dump($result);
		
		$this->display();
    }
	public function edit_password()
	{
		$this->display();
    }
	public function edit_password_save()
	{
		$usrid = $_SESSION [C ( 'USER_AUTH_KEY' )];
		$oldpwd = $_POST['password'];
        $newpwd1 = $_POST['newpass1'];
		$newpwd2 = $_POST['newpass2'];
		
		$this->assign("jumpUrl",U('Index/edit_password'));
		
		if(empty($oldpwd))
		{
			$this->error ('原始密码不能为空');			
		}
		else if(empty($newpwd1) || empty($newpwd2))
		{
			$this->error ('新密码不能为空');
		}
		else if($newpwd1!=$newpwd2)
		{
			$this->error ('两次新密码不一致');
		}
		else
		{
			//生成认证条件
			$map = array();
			$map["where"]["id"] = $usrid;
			$map["where"]["password"]= md5($oldpwd);

			$user = M('User');
			$account = $user->find($map);

			if (!$account) 
			{
				$this->error("原始密码错误！");
			}
			else 
			{
				$data['id'] = $usrid;
				$data["password"] = md5($newpwd1);
				$data['updated'] = time();
				//var_dump($newpwd1);var_dump($data);
				$user->save($data);
				$this->success("修改成功,请记住新密码!");
			}			
		}		
    }
	
	public function account_add()
    {
		$this->display();
    }
	
	public function account_add_save()
    {
		$admin = D("User"); // 实例化admin对象
		$this->assign("jumpUrl",U('Index/account_list'));
		if ($admin->create())
		{			
			$admin->updated = time();
			$admin->password = md5($_POST['password']);
			// 创建数据对象成功，写入数据
			$admin->add(); // 保存数据
			$this->success("创建成功!");			
		}
		else
		{
			// 创建数据对象失败
			$this->error($admin->getError());
		}		
    }
	
	public function account_list()
    {
		$acc_list = M("User") -> order("id asc")->select();
		$this->assign("acc_list",$acc_list);
		$this->display();
    }
	
	public function account_edit()
    {
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= M("User");
        $account = $model->find($map);
		$this->assign("account",$account);
		$this->display();
    }
	
	public function account_edit_save()
    {
		$admin = D("User"); // 实例化admin对象
		$this->assign("jumpUrl",U('Index/account_list'));
		if ($admin->create())
		{
			if($_POST['password1'])
			{
				$admin->password = md5($_POST['password1']);
			}
			$admin->updated = time();
			// 创建数据对象成功，写入数据
			$admin->save(); // 保存数据
			$this->success("保存成功!");			
		}
		else
		{
			// 创建数据对象失败
			$this->error($admin->getError());
		}		
    }
	
	public function account_del()
    {
		$admin = M("User"); // 实例化admin对象
		$this->assign("jumpUrl",U('Index/account_list'));
		$admin->where("id in (".$_GET["id"].")")->delete(); // 删除用户数据
		//var_dump("id in (".$_GET["id"].")");exit();
		if ($admin)
		{
			// 成功
			$this->success("删除成功!");			
		}
		else
		{
			// 失败
			$this->error($admin->getError());
		}		
    }
	
	public function account_popup()
	{
		$objid=$_REQUEST['objid'];
		$objcode=$_REQUEST['objcode'];
		$objtitle=$_REQUEST['objtitle'];
		$this->assign("objid",$objid);
		$this->assign("objcode",$objcode);
		$this->assign("objtitle",$objtitle);
		
		$keywords = $_REQUEST['keywords'];
		$this->assign('keywords',$keywords);
		
		import("ORG.Util.Page"); // 导入分页类
		
		$model=M("User");
		$strwhere="status_flg in ('Y') and (username like '%$keywords%')";
		
		$count      = $model->where($strwhere)->count(); // 查询满足要求的总记录数
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&cid=".urlencode($cid);   //传递查询条件
		$Page->parameter   .=   "&keywords=".urlencode($keywords);
		$Page->parameter   .=   "&objid=".urlencode($objid);
		$Page->parameter   .=   "&objcode=".urlencode($objcode);
		$Page->parameter   .=   "&objtitle=".urlencode($objtitle);
		
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->where($strwhere) -> order("role desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出		
		
		$this->display();
    }
	
	public function web_config()
	{
		$config_list = M("Webconfig") -> order("vargroup asc,orderid asc")->select();
		$this->assign("config_list",$config_list);
		$this->display();
	}
	
	public function web_config_add_save()
	{
		$model = D("Webconfig");
		if($model->create())
		{
			$model->add();
			//$configfile = C('APP_PATH_DIY').'/web_config_diy.php';
			
			S('web_config_diy',null);
			
			//$data_upd['code']=md5('web_config');
			//$data_upd['html']=md5(md5_file($configfile));
			//M('Test')->data($data_upd)->where("code = '".$data_upd['code']."'")->save();
			
			
			$this->success("新增成功!");
		}
		else
		{
			$this->error($model->getError());
		}
	}
	
	public function web_config_save()
	{
		$model = M("Webconfig");
		$this->assign("jumpUrl",U('Index/web_config'));
		foreach($_POST as $k=>$v)
		{
			
			$data["varvalue"] = $v;
			$result = $model->where("varname='$k'")->save($data);
		}

		//$configfile = dirname(dirname(dirname(__file__))).'/Conf/web_config_diy.php';
		//$configfile = C('APP_PATH_DIY').'/web_config_diy.php';
		
		S('web_config_diy',null);
		
		
		//$data_upd['code']=md5('web_config');
		//$data_upd['html']=md5(md5_file($configfile));
		//M('Test')->data($data_upd)->where("code = '".$data_upd['code']."'")->save();

	
		$this->success("修改成功!");
	}
	public function web_config_del()
    {
		$model = M("Webconfig");
		//$this->assign("jumpUrl",U('Index/web_config'));
		if ($model->where("varname='".$_GET["var"]."'")->delete())
		{
			$this->success("删除成功!");			
			
			S('web_config_diy',null);
		}
		else
		{
			$this->error($model->getError());
		}		
    }
	public function uploadbox()
	{
		header("Content-Type:text/html; charset=utf-8");
		$this->assign("objid",$_GET['objid']);
		//echo "需要上传的对像为：".$_GET['objid'];
		$this->display();
	}
	public function upload_save()
	{
		import("ORG.Net.UploadFile");
		$upload = new UploadFile(); // 实例化上传类
		$upload->maxSize = C('UPLOAD_ALLOW_SIZE') ; // 设置附件上传大小
		$upload->allowExts = explode(',',str_ireplace('php','abc',strtolower(C('UPLOAD_ALLOW_EXTS')))); // 设置附件上传类型
		$upload->savePath = '.'.C('UPLOAD_PATH'); // 设置附件上传目录
		$upload->saveRule = C('UPLOAD_RULE');
		if(!$upload->upload()) 
		{
			// 上传错误 提示错误信息
            echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
			echo $upload->getErrorMsg();
		}
		else
		{ // 上传成功 获取上传文件信息
			$info = $upload->getUploadFileInfo();
		}
		//$upload_info="<b>文件上传成功</b><br>以下是本次上传结果,如有需要,请记录:<br><br>";
		foreach($info as $file)
		{
			$upload_info.="".C('UPLOAD_PATH').$file["savename"]."";
		}
		//$this->assign('upload_info',$upload_info);  
		//$this->display();
		if($_POST['objid']=="sysupdate")
		{
			echo "<script type='text/javascript'>window.location.href='".U('Index/sysupdate?objsign='.$_POST['objsign'].'&zfile='.str_ireplace('/','~',$upload_info).'')."';</script>";
		}
		else if($_POST['objid']=="dialog")
		{
			echo "<script type='text/javascript'>parent.window.returnValue='".$upload_info."';parent.window.close();</script>";
		}
		else if($_POST['objid']=="print")
		{
			echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
			echo "<center><div style='width:400px; font-size:12px; margin:30px auto; text-align:left;'><b>文件上传成功</b><br>以下是本次上传结果,请记录所需信息:<br><br>".$upload_info."</div></center>";
		}
		else
		{
			echo "<script type='text/javascript'>window.parent.document.getElementById('".$_POST['objid']."').value='".$upload_info."';parent.close_upload_window();</script>";
		}
		
	}
	public function today()
	{
		//check_system();
		
		//今日销售情况
		//$subQuery = M('Spmas')->field('id')->where("mas_code in ('SO') and status_flg in ('P') and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m%d'),'".date('Ymd')."') = 0")->select(false);
		$subQuery = M('Spmas')->field('id')->where("mas_code in ('SO') and status_flg in ('P') and fadate = ".strtotime(date('Y-m-d'))." ")->select(false);
		$info_so=M('Spitem')->field('sum(qty) as qty,sum(amount2) as amount2')->where('masid in '.$subQuery)->find();
		$this->assign('info_so',$info_so);
		$subQuery = M('Spmas')->field('id')->where("mas_code in ('RNC') and status_flg in ('P') and fadate = ".strtotime(date('Y-m-d'))." ")->select(false);
		$info_rnc=M('Spitem')->field('sum(qty) as qty,sum(amount2) as amount2')->where('masid in '.$subQuery)->find();
		$this->assign('info_rnc',$info_rnc);
		
		//今日采购情况
		$subQuery = M('Spmas')->field('id')->where("mas_code in ('PO') and status_flg in ('P') and fadate = ".strtotime(date('Y-m-d'))." ")->select(false);
		$info_po=M('Spitem')->field('sum(qty) as qty,sum(amount2) as amount2')->where('masid in '.$subQuery)->find();
		$this->assign('info_po',$info_po);
		$subQuery = M('Spmas')->field('id')->where("mas_code in ('RNS') and status_flg in ('P') and fadate = ".strtotime(date('Y-m-d'))." ")->select(false);
		$info_rns=M('Spitem')->field('sum(qty) as qty,sum(amount2) as amount2')->where('masid in '.$subQuery)->find();
		$this->assign('info_rns',$info_rns);
		
		//实时库存情况
		//$info_stk=D('StkdetailView')->field('wh_title,sum(open_qty) as open_qty,sum(open_amount) as open_amount')->group('wh_title')->select();
		$info_stk=M('Stkdetail')->field('sum(open_qty) as open_qty,sum(open_amount) as open_amount')->find();
		$this->assign('info_stk',$info_stk);
		$model_stk = D('StkmasView');
		$subQuery = $model_stk->field('id,qty_min,sum(open_qty) as open_qty')->where('qty_min>0')->group('id')->select(false);
		$info_stk_min=$model_stk->table($subQuery.' as a')->where('IFNULL(open_qty,0) < qty_min')->count();
		$this->assign('info_stk_min',$info_stk_min);
		$subQuery = $model_stk->field('id,qty_max,sum(open_qty) as open_qty')->where('qty_max>0')->group('id')->select(false);
		$info_stk_max=$model_stk->table($subQuery.' as a')->where('IFNULL(open_qty,0) > qty_max')->count();
		$this->assign('info_stk_max',$info_stk_max);
		
		$acc_array = explode(',',C('TODAY_FA_ACC'));
		foreach($acc_array as $acc)
		{
			$info_acc[$acc]['acc_code']=$acc;
			$info_acc[$acc]['acc_title']=M('Faccmas')->where('code=\''.$acc.'\'')->getField('title');
			$info_acc[$acc]['acc_closing']=get_acc_closing($acc);
		}
		$this->assign('info_acc',$info_acc);
		
		
		//C('SHOW_PAGE_TRACE',true);
		$this->display();
	}
	
	public function help()
	{
		header("Content-Type:text/html; charset=utf-8");
		$html = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
		$html .= "<html>";
		$html .= "<head>";
		$html .= "<title>帮助主题</title>";
		$html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
		$html .= '<style>';
		$html .= "html, body{margin:0; padding:0; border:0 none;font-family: 'Microsoft Yahei', Verdana, arial, sans-serif;font-size:14px;line-height:150%;background:white}";
		$html .= "div.message{margin:10% auto 0px auto;clear:both;padding:5px;border:0px solid silver; text-align:center; width:90%}";
		$html .= "a {COLOR: #416AA3; TEXT-DECORATION: none}";
		$html .= "a:link {COLOR: #416AA3; TEXT-DECORATION: none}";
		$html .= "a:hover {COLOR: #333; TEXT-DECORATION: none}";
		$html .= "</style>";
		$html .= "</head>";
		$html .= "<body>";
		$html .= '<div class="message">';
		$html .= '<img src="../../Public/Images/help_ico.png" /><br /><br />';
		$html .= '<a href="'.C('OFFICIAL_HELP').'" target="_blank"><span style="font-size:15px;">书到用时方恨少，现在就去练功！</span></a>';
		$html .= '</div>';
		$html .= '</body>';
		$html .= '</html>';
		echo $html;
		//$this->display();
	}
	public function about()
	{
		check_system();
		header("Content-Type:text/html; charset=utf-8");
		$html = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
		$html .= "<html>";
		$html .= "<head>";
		$html .= "<title>关于本系统</title>";
		$html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
		$html .= '<style>';
		$html .= "html, body{margin:0; padding:0; border:0 none;font-family: 'Microsoft Yahei', Verdana, arial, sans-serif;font-size:14px;line-height:150%;background:white}";
		$html .= "div.message{margin:10% auto 0px auto;clear:both;padding:5px;border:0px solid silver; text-align:center; width:90%}";
		$html .= "a {COLOR: #416AA3; TEXT-DECORATION: none}";
		$html .= "a:link {COLOR: #416AA3; TEXT-DECORATION: none}";
		$html .= "a:hover {COLOR: #333; TEXT-DECORATION: none}";
		$html .= "</style>";
		$html .= "</head>";
		$html .= "<body>";
		$html .= '<div class="message">';
		$html .= '<img src="../../Public/Images/notice_right.gif" /><br /><br />';
		$html .= '<span style="font-size:15px;">本【'.C('OFFICIAL_NAME').' 进销存财-'.C('REGISTER_VER').'】系统，已授权给【'.C('WEB_TITLE').'】使用</span>';
		$html .= '</div>';
		$html .= '</body>';
		$html .= '</html>';
		echo $html;
	}
	
	public function sysupdate()
	{
		header("Content-Type:text/html; charset=utf-8");
        
        $signcode = $_REQUEST['objsign'];
        if(!$signcode)
        {
            echo '没有校验说明';
            exit;
        }else if($signcode != md5(md5(date('Y-m-d').'-misone'))){
            echo '校验失败';
            exit;
        }
        
        Vendor('pclzip.pclziplib');
        
		echo '<ul>';
		
		$zfile = $_REQUEST['zfile'];
		
		if(!$zfile)
		{
			//$this->error('没有可升级文件');exit;
			echo '<li>没有可升级文件 '.date('Y-m-d H:i:s').'</li></ul>';exit;
		}
		else
		{
			$zfile = str_ireplace('~','/',$zfile);
		}
		echo '<li>升级包文件： '.$zfile.'</li>';
        
        $archive = new PclZip(C('APP_PATH_DIY').$zfile);
 
        if ($archive->extract(PCLZIP_OPT_PATH,C('APP_PATH_DIY')) == 0) {
            //die("Error : ".$archive->errorInfo(true));
            echo '<ul><li>失败:'.$archive->errorInfo(true).'</li></ul>';
        }else{
			
			echo '<li>程序文件已更新 '.date('Y-m-d H:i:s').'</li>';
			
			//更新数据库
			$db_update_file = C('APP_PATH_DIY').'/DbUpdate/update.sql';
			Vendor('Myinitdb.Myinitdb');
			$myinitdb = new Myinitdb();
			
			$tbdata = '';
			if(file_exists($db_update_file)) $tbdata = $myinitdb->Readf($db_update_file);
			if($tbdata)
			{
			
				$Model = new Model(); // 实例化一个model对象 没有对应任何数据表
				$querys = explode(';', $tbdata);
				foreach($querys as $q)
				{
					if(trim($q) == '') continue;
					$Model->execute(trim($q));
					echo '<li>更新数据库 '.date('Y-m-d H:i:s').'</li>';
				}
			
			}
			if(file_exists($db_update_file)) rename($db_update_file,$db_update_file.date('YmdHis').'.sql');
			
		}
		echo '</ul>';
	}
    
    public function sysupdate_local()
	{
		header("Content-Type:text/html; charset=utf-8");
		echo '<ul>';
		
		$zfile = $_REQUEST['zfile'];
		
		if(!$zfile)
		{
			//$this->error('没有可升级文件');exit;
			echo '<li>没有可升级文件 '.date('Y-m-d H:i:s').'</li></ul>';exit;
		}
		else
		{
			$zfile = str_ireplace('~','/',$zfile);
		}
		echo '<li>升级包文件： '.$zfile.'</li>';
		//var_dump($zfile);
		/*
		通过ZipArchive的对象处理zip文件
		$zip->open这个方法的参数表示处理的zip文件名。
		如果对zip文件对象操作成功，$zip->open这个方法会返回TRUE
		覆盖解压
		*/
		$zip = new ZipArchive;//新建一个ZipArchive的对象
		if ($zip->open(C('APP_PATH_DIY').$zfile) === TRUE)
		{
			$zip->extractTo(C('APP_PATH_DIY'));//假设解压缩到在当前路径下TEST
			$zip->close();//关闭处理的zip文件
			
			echo '<li>程序文件已更新 '.date('Y-m-d H:i:s').'</li>';
			
			//更新数据库
			$db_update_file = C('APP_PATH_DIY').'/DbUpdate/update.sql';
			Vendor('Myinitdb.Myinitdb');
			$myinitdb = new Myinitdb();
			
			$tbdata = '';
			if(file_exists($db_update_file)) $tbdata = $myinitdb->Readf($db_update_file);
			if($tbdata)
			{
			
				$Model = new Model(); // 实例化一个model对象 没有对应任何数据表
				$querys = explode(';', $tbdata);
				foreach($querys as $q)
				{
					if(trim($q) == '') continue;
					$Model->execute(trim($q));
					echo '<li>更新数据库 '.date('Y-m-d H:i:s').'</li>';
				}
			
			}
			if(file_exists($db_update_file)) rename($db_update_file,$db_update_file.date('YmdHis').'.sql');
			
		}
		else
		{
			echo '<ul><li>压缩档案读取失败</li></ul>';
		}
		echo '</ul>';
	}
	
	
	

}
?>